package models

import (
	"errors"
	"gorm.io/gorm"
	"strings"
)

// AgentApplyWithdrawalCache 代理商申请提现缓存表
type AgentApplyWithdrawalCache struct {
	ID           uint    `json:"id" form:"id" gorm:"primary_key;AUTO_INCREMENT;comment:'id'"`
	Type         int     `json:"type,omitempty" gorm:"comment:'0=未删除 1=已删除'"`
	AgentId      int     `json:"agentId,omitempty" gorm:"comment:'代理商id'"`
	Month        string  `json:"month" gorm:"comment:'时间'"`
	BeforeAmount float32 `json:"beforeAmount" gorm:"type:decimal(10,2);comment:'税前'"`
	TaxAmount    float32 `json:"tax_amount" gorm:"type:decimal(8,6);comment:'税率'"`
	AfterAmount  float32 `json:"afterAmount" gorm:"type:decimal(10,2);comment:'税后'"`
	OrderIds     string  `json:"order_ids,omitempty" gorm:"comment:'订单id集合'"`
}

// AgentApplyWithdrawalCacheCreate 添加缓存记录
func AgentApplyWithdrawalCacheCreate(apply *AgentApplyWithdrawalCache) (*AgentApplyWithdrawalCache, error) {
	var temps []*AgentApplyWithdrawalCache
	if err := db.Model(&AgentApplyWithdrawalCache{}).Where("agent_id = ? AND type = 0 AND month = ?", apply.AgentId, apply.Month).Scan(&temps).Error; err == nil {
		//有这条数据
		db.Model(&temps).Update("type", 1)
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	err := db.Create(&apply).Error
	if err != nil {
		return nil, err
	}
	apply.AgentId = 0
	apply.OrderIds = ""
	apply.Type = 0
	return apply, nil
}

// AgentApplyWithdrawalCacheGet 获取记录数据
func AgentApplyWithdrawalCacheGet(ids string) ([]*AgentApplyWithdrawalCache, error) {
	var models []*AgentApplyWithdrawalCache
	if err := db.Model(&AgentApplyWithdrawalCache{}).Where("FIND_IN_SET(id,?)", ids).Scan(&models).Error; err != nil {
		return nil, err
	}
	if strings.Count(ids, ",")+1 != len(models) {
		return nil, errors.New("数据不存在")
	}
	return models, nil
}
